package com.tc.interceptor;

import com.tc.service.impl.AuthServiceImpl;
import com.tc.utils.JWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * JWT令牌拦截器
 * </p>
 *
 * @author tc
 * @since 2025-07-10
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private AuthServiceImpl authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 跳过登录、验证码等公开接口
        String requestURI = request.getRequestURI();
        if (isPublicPath(requestURI)) {
            return true;
        }

        // 获取token
        String token = getTokenFromRequest(request);
        if (!StringUtils.hasText(token)) {
            response.setStatus(401);
            response.getWriter().write("{\"code\":401,\"message\":\"未授权访问\"}");
            return false;
        }

        // 验证token
        if (!JWT.validateToken(token)) {
            response.setStatus(401);
            response.getWriter().write("{\"code\":401,\"message\":\"令牌无效或已过期\"}");
            return false;
        }

        // 检查token是否在黑名单中
        if (authService.isTokenBlacklisted(token)) {
            response.setStatus(401);
            response.getWriter().write("{\"code\":401,\"message\":\"令牌已失效\"}");
            return false;
        }

        return true;
    }

    /**
     * 判断是否为公开路径
     */
    private boolean isPublicPath(String path) {
        return path.startsWith("/auth/") || 
               path.startsWith("/doc.html") || 
               path.startsWith("/webjars/") || 
               path.startsWith("/swagger-resources") || 
               path.startsWith("/v2/api-docs");
    }

    /**
     * 从请求中获取令牌
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
